<script setup lang="ts">
  import { reactive, ref, watch, PropType } from 'vue'
  import _ from 'lodash'
  import { ElMessage, FormInstance } from 'element-plus'
  import HButton from '@/components/common/button/HButton.vue'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import {
    useNetworkOptionsService,
    useNetworkEmpOptionsService,
    useNetworkTypeOptionsService,
    useWaitCheckWorkReassignService,
  } from './services'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import { CheckWorkReassignAllow, CheckWorkReassignReject } from './types'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const props = defineProps({
    network: {
      type: String,
      required: true,
    },
    networkId: {
      type: String,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    address: Object as PropType<{
      province: string
      city: string
      area: string
      town: string
      address: string
    }>,
  })

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'update:modelValue', value: boolean): void
    (e: 'close'): void
  }>()

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService(['changeToNetworkId'])

  // 表单
  const form = ref({
    changeToNetworkId: '',
    checkTypep: 1,
    id: '',
    networkEmpId: '',
    remark: '',
  })

  // 弹窗的显示状态
  const visible = ref(false)

  // 表单校验规则
  const rules = reactive({
    changeToNetworkId: [{ required: true, message: '请选择服务商！', trigger: ['blur', 'change'] }],
  })

  // 表单组件实例
  const formRef = ref<FormInstance>()

  /**
   * 审核通过事件
   */
  const onAllow = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validateField()
        const temp: CheckWorkReassignAllow = {
          changeToNetworkId: form.value.changeToNetworkId,
          remark: form.value.remark,
          id: form.value.id,
          networkEmpId: form.value.networkEmpId,
        }
        const res = await allow(temp, props.orderId)
        emits('update')
        visible.value = false
        emits('update:modelValue', visible.value)
        ElMessage({
          type: res.success ? 'success' : 'error',
          message: res.message,
        })
      } catch (e) {
        // 校验不通过
      }
    }
  }

  /**
   * 驳回审核事件
   */
  const onReject = async () => {
    const temp: CheckWorkReassignReject = {
      remark: form.value.remark,
      id: form.value.id,
    }
    const res = await reject(temp, props.orderId)
    emits('update')
    visible.value = false
    emits('update:modelValue', visible.value)
    ElMessage({
      type: res.success ? 'success' : 'error',
      message: res.message,
    })
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    form.value.changeToNetworkId = ''
    visible.value = false
    form.value.remark = ''
    form.value.networkEmpId = ''
    networkType.value = ''
    filterType.value = 0
    addr.value = {
      city: '',
      area: '',
      province: '',
      town: '',
    }
    resetFormValidateResult()
    emits('close')
    emits('update:modelValue', visible.value)
  }

  // 使用获取待审核改派服务商的工单服务
  const {
    waitCheckWorkReassign,
    checkWorkReassignLoading,
    getWaitCheckWorkReassignLoading,
    allow,
    reject,
    getWaitCheckReassign,
  } = useWaitCheckWorkReassignService

  // 使用服务商选项服务
  const { getNetworkOptions, getNetworkOptionsLoading, getNetworkOptionsParam, networkOptions } =
    useNetworkOptionsService

  // 使用服务人员选项服务
  const {
    getNetworkEmpOptions,
    getNetworkEmpOptionsParam,
    getNetworkEmpOptionsLoading,
    networkEmpOptions,
  } = useNetworkEmpOptionsService

  const {
    networkTypeOptions,
    getNetworkTypeOptionsParam,
    getNetworkTypeOptionsLoading,
    getNetworkTypeOptions,
  } = useNetworkTypeOptionsService

  /**
   * 获取服务商选项方法
   */
  const getNetworkOptionsFn = () => {
    Object.assign(getNetworkOptionsParam.value, {
      area: [0, 1].includes(filterType.value) ? '' : addr.value.area,
      city: [0, 1].includes(filterType.value) ? '' : addr.value.city,
      limit: 0,
      page: 0,
      province: [0, 1].includes(filterType.value) ? '' : addr.value.province,
      type: filterType.value,
      typeId: [0, 2].includes(filterType.value) ? null : networkType.value,
    })
    if (getNetworkOptionsParam.value.typeId === '0') {
      getNetworkOptionsParam.value.typeId = ''
    }
    getNetworkOptions()
  }

  /**
   * 获取服务商选项
   */
  const getNetworkPageSelectList = _.throttle((query: string) => {
    if (query === getNetworkOptionsParam.value.name) {
      return false
    }
    getNetworkOptionsParam.value.name = query
    getNetworkOptionsFn()
  }, 500)

  /**
   * 获取分配人员选项
   */
  const getNetworkEmpPageSelectList = _.throttle((query: string) => {
    // 服务没有选择服务商就不获取
    if (!form.value.changeToNetworkId || getNetworkEmpOptionsParam.value.name === query) return
    getNetworkEmpOptionsParam.value.name = query
    getNetworkEmpOptionsFn()
  }, 500)

  // 判断是否是个人
  const isTeamType = ref(false)

  /**
   * 获取服务人员选项方法
   */
  const getNetworkEmpOptionsFn = async () => {
    await getNetworkEmpOptions(form.value.changeToNetworkId)
    let arr = networkOptions.value.filter((o) => o.id == form.value.changeToNetworkId)
    isTeamType.value = false
    if (arr[0].teamType === 2) {
      form.value.networkEmpId = networkEmpOptions.value[0].id
      isTeamType.value = true
    }
  }

  // 服务商分类
  const networkType = ref('0')

  /**
   * 获取服务商类型
   */
  const getNetworkTypeSelectList = _.throttle((query: string) => {
    if (getNetworkTypeOptionsParam.value.name === query) return
    getNetworkTypeOptionsParam.value.name = query
    getNetworkTypeOptions()
  }, 500)

  /**
   * 查询条件
   * 0 - 全部
   * 1 - 服务商分类
   * 2 - 按省市区
   */
  const filterType = ref(0)

  // 服务范围
  const addr = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 地址组件实例
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null)

  /**
   * 获取服务范围
   */
  const handleChangeAddress = () => {
    if (singleAddressRef.value) {
      Object.assign(addr.value, singleAddressRef.value.getSelectAddr())
      getNetworkOptionsFn()
    }
  }

  /**
   * 清空地址
   */
  const onClearAddress = () => {
    addr.value.province = ''
    addr.value.area = ''
    addr.value.city = ''
    addr.value.town = ''
    filterType.value = 0
    getNetworkOptionsFn()
  }

  /**
   * 查询条件更新事件
   * @param {number} val - 条件的值: 1.全部 2.按服务商分类 3.客户地址
   */
  const onChangeCondition = async (val: 0 | 1 | 2 | 3) => {
    if (formRef.value) {
      formRef.value.resetFields()
      addr.value.province = ''
      addr.value.area = ''
      addr.value.city = ''
      addr.value.town = ''
    }
    if (val === 3 || val === 2) {
      if (props.address) {
        filterType.value = val
        addr.value.province = props.address.province
        addr.value.city = props.address.city
        addr.value.area = props.address.area
        addr.value.town = props.address.town
      }
    }
    if (val === 1) {
      await getNetworkTypeOptions()
    } else {
      getNetworkOptionsFn()
    }
  }
  /**
   * 显示弹窗事件
   */
  const onShowModal = async () => {
    visible.value = true
    if (props.address) {
      filterType.value = 3
      addr.value.province = props.address.province
      addr.value.city = props.address.city
      addr.value.area = props.address.area
      addr.value.town = props.address.town
    } else {
      await getNetworkTypeOptions()
    }
    getNetworkOptionsFn()
  }

  /**
   * 更新服务商事件
   */
  const onChangeNetwork = async () => {
    form.value.networkEmpId = ''
    await getNetworkEmpOptionsFn()
  }

  /**
   * 服务商分类选择事件
   */
  const handleChangeNetworkType = () => {
    form.value.changeToNetworkId = ''
    getNetworkOptionsFn()
  }

  watch(
    () => props.modelValue,
    async (value) => {
      visible.value = value
      if (value) {
        if (props.address) {
          filterType.value = 3
          addr.value.province = props.address.province
          addr.value.city = props.address.city
          addr.value.area = props.address.area
          addr.value.town = props.address.town
        } else {
          await getNetworkTypeOptions()
        }
        getNetworkOptionsFn()
        await getWaitCheckReassign(props.orderId)
        form.value.id = waitCheckWorkReassign.value.id
      }
    },
    { immediate: true },
  )
</script>

<template>
  <div>
    <span @click="onShowModal">
      <slot></slot>
    </span>

    <HModal title="审核改派服务商申请" v-model="visible" @close="onCancel" width="auto">
      <div v-loading="checkWorkReassignLoading || getWaitCheckWorkReassignLoading">
        <div class="alert_container">
          <el-alert
            class="alert"
            show-icon
            :closable="false"
            title="改派后，该工单不再属于原服务商"
            type="warning"
          />
        </div>
        <el-form
          label-width="82"
          ref="formRef"
          :rules="rules"
          :model="form"
          @validate="handleFormValidate"
          class="modal_form_content"
        >
          <!--当前服务商-->
          <el-form-item label="当前服务商" class="form_input_item">
            <el-input disabled :value="props.network" />
          </el-form-item>

          <!-- 查询条件 -->
          <el-form-item label="查询条件" class="form_select_item">
            <el-select
              placeholder="请选择查询条件"
              filterable
              v-model="filterType"
              @blur.stop="() => {}"
              @change="onChangeCondition"
            >
              <el-option :value="0" label="全部" />
              <el-option :value="1" label="按服务商分类" />
              <el-option :value="2" label="服务区域" />
              <el-option :value="3" label="客户地址" />
            </el-select>
          </el-form-item>

          <!-- 服务范围 -->
          <el-form-item
            :label="filterType === 3 ? '客户地址' : '服务区域'"
            v-if="filterType === 3 || filterType === 2"
            class="form_select_item"
          >
            <SingleAddress
              :address="addr"
              ref="singleAddressRef"
              @value-change="handleChangeAddress"
              checkStrictly
              @clear="onClearAddress"
            />
          </el-form-item>

          <!-- 服务商分类 -->
          <el-form-item label="服务商分类" v-if="filterType === 1" class="form_select_item">
            <el-select
              placeholder="服务商分类"
              filterable
              v-model="networkType"
              :filter-method="getNetworkTypeSelectList"
              :loading="getNetworkTypeOptionsLoading"
              remote-show-suffix
              @change="handleChangeNetworkType"
            >
              <el-option value="0" label="全部" />
              <el-option
                v-for="item in networkTypeOptions"
                :key="item.name"
                :disabled="networkId === item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <!-- 分配服务商 -->
          <el-form-item
            label="分配服务商"
            required
            prop="changeToNetworkId"
            class="form_select_item"
            :class="{ error_form_item: !formValidateResult['changeToNetworkId'] }"
          >
            <el-select
              placeholder="分配服务商"
              filterable
              v-model="form.changeToNetworkId"
              :filter-method="getNetworkPageSelectList"
              :loading="getNetworkOptionsLoading"
              remote-show-suffix
              @change="onChangeNetwork"
            >
              <el-option
                v-for="(item, index) in networkOptions"
                :key="index"
                :disabled="networkId === item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <!-- 分配人员 -->
          <el-form-item label="分配人员" v-if="!isTeamType" class="form_select_item">
            <el-select
              v-model="form.networkEmpId"
              placeholder="分配人员"
              filterable
              :filter-method="getNetworkEmpPageSelectList"
              :loading="getNetworkEmpOptionsLoading"
              remote-show-suffix
              clearable
            >
              <el-option
                v-for="item in networkEmpOptions"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" class="form_textarea_item">
            <el-input
              v-model="form.remark"
              maxlength="200"
              placeholder="请输入备注"
              show-word-limit
              type="textarea"
              resize="both"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footerLeft>
        <HPlainBgButton is-modal type="error" @click="onReject" :loading="checkWorkReassignLoading"
          >驳回</HPlainBgButton
        >
      </template>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onAllow" :loading="checkWorkReassignLoading"
          >审核通过</HButton
        >
        <HButton isModal @click="onCancel" :loading="checkWorkReassignLoading">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './CheckUpdateNetwork.scss';
</style>
